/**
 * 日期格式化
 *
 * @param {}
 *            d 输入日期 例：20110915222430
 * @return {} 返回格式化日期 2011年09月15日 22:24:30
 */
DateFormat = function(d) {
	date = d.toString();
	var year = date.substr(0, 4);
	var month = date.substr(4, 2);
	var day = date.substr(6, 2);
	var hour = date.substr(8, 2);
	var min = date.substr(10, 2);
	var sec = date.substr(12, 2);
	return year + "年" + month + "月" + day + " " + hour + ":" + min + ":" + sec;
};

Date.prototype.format = function(format) {

	var o = {
		"M+" : this.getMonth() + 1, // month
		"d+" : this.getDate(), // day
		"h+" : this.getHours(), // hour
		"m+" : this.getMinutes(), // minute
		"s+" : this.getSeconds(), // second
		"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
		"S" : this.getMilliseconds()
		// millisecond
	};

	if(/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}

	for(var k in o) {
		if(new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
};
/**
 * 扩展js function对象的代理方法
 *
 * @param {}
 *            obj
 * @param {}
 *            args
 * @param {}
 *            appendArgs
 * @return {}
 */
Function.prototype.createDelegate = function(obj, args, appendArgs) {
	var method = this;
	return function() {
		var callArgs = args || arguments;
		if(appendArgs === true) {
			callArgs = Array.prototype.slice.call(arguments, 0);
			callArgs = callArgs.concat(args);
		} else if( typeof appendArgs === 'number' && isFinite(appendArgs)) {
			callArgs = Array.prototype.slice.call(arguments, 0);
			// copy
			// arguments
			// first
			var applyArgs = [appendArgs, 0].concat(args);
			// create method
			// call params
			Array.prototype.splice.apply(callArgs, applyArgs);
			// splice them
			// in
		}
		;
		return method.apply(obj || window, callArgs);
	};
};
/**
 * 扩展js function对象的集成方法
 *
 * @param {}
 *            parentClass
 */
Function.prototype.Extends = function(parentClass) {
	var Bs = new Function();
	Bs.prototype = parentClass.prototype;
	this.prototype = new Bs();
	this.prototype.Super = parentClass;
	this.prototype.constructor = this;
};
function preLoadImg(src, callback) {
	var img = new Image();
	img.src = src;
	/*	if (img.complete){// 如果图片已经存在于浏览器缓存，直接调用回调函数
	 // callback.call(thumbImg);
	 return; // 直接返回，不用再处理onload事件
	 }
	 img.onload = function(){ // 图片下载完毕时异步调用callback函数。
	 // callback.call(thumbImg);//将回调函数的this替换为Image对象
	 };*/
	return img;
};

var Tfeet = {
	version : "1.1",
	widgets : {},
	apply : function(o, c, defaults) {
		if(defaults) {
			Tfeet.apply(o, defaults);
		}
		if(o && c && typeof c == 'object') {
			for(var p in c) {
				o[p] = c[p];
			}
		}
		return o;
	}
};

/**
 * 基类
 */
Tfeet.Base = function() {
	this.uid = null;
	this.uname = null;
	this.key = null;
	this.data = {};
};

Tfeet.Tfobj = function(config) {
	this.tfid = null;
	this.ds = {};
	this.location = null;
	this.description = null;
	this.lon = null;
	this.lat = null;
	this.orgImg = null;
	this.thumbImg = null;
	this.initComponent = function(config) {
		Tfeet.apply(this, config);
	};

	this.initComponent(config);
};

/**
 *
 * @returns {Tfeet.Store}
 */
Tfeet.Store = function(config) {
	this.baseUrl = "./i/getfeet/";
	//this.url = "data/feet.json";
	this.selectedIndex = 0;
	this.type = "all";
	this.tfeetCacheList = null;
	this.initComponent = function(config) {
		this.tfeetCacheList = new Array();
		Tfeet.apply(this, config);
	};
	/**
	 * 组装请求url
	 * getNew 顺序（true:取新的20
	 * 条数据；false:取之前的20条数据 ）
	 */
	this.doLoadParam = function(option) {
		var url = this.baseUrl;
		if(this.type) {
			url += this.type + "?";
		}
		if(this.type == 'all') {
			url += "uid=0";
		} else {
			url += "uid=" + this.uid;
		}
		if(option.startIndex && option.startIndex >= 0) {
			url += "&tfid=" + (this.tfeetCacheList.length - 1);
		} else {
			url += "&tfid=0";
		}
		return url += "&since_id=0";
	};
	/**
	 * 加载数据
	 * option ajax请求参数
	 * scope
	 */
	this.load = function(startIndex, buffer,init) {
		if(init){
			var option = {
				startIndex : 0,
				buffer : 10,
				init :init
			};
			this.loadAjax(option, this);
		}
		/* 缓冲区为空或者当前 */
		if(this.tfeetCacheList.length == 0) {
			var option = {
				startIndex : startIndex,
				buffer : buffer
			};
			this.loadAjax(option, this);
			return;
		}
		if(startIndex < 0) {
			startIndex = 0;
			var option = {
				startIndex : startIndex,
				buffer : buffer
			};
			this.loadAjax(option, this);
			return;
		}
		if((this.tfeetCacheList.length>buffer&&startIndex + buffer >= this.tfeetCacheList.length)||startIndex+buffer<0) {
			var option = {
				startIndex : startIndex,
				buffer : buffer
			};
			this.loadAjax(option, this);
			return;
		}
		this.trigger("Load", [startIndex, buffer]);
	};

	this.loadCacheList = function() {

	};

	this.loadAjax = function(option, scope) {
		var url = this.doLoadParam(option);
		//svar options = {};
		options = {
			url : url,
			type : "get",
			dataType : "json",
			beforeSend : function(event) {
				event.setRequestHeader("XSRCKEY", this.key);
			}.createDelegate(this)
		};
		//Tfeet.apply(options, option);
		jQuery.ajax(options).done( function(data, textStatus, scope) {
			this.createRequestCallback(data, textStatus, this, option);
		}.createDelegate(this)).fail(this.createRequestErrorCallback(option, scope));
		return true;
	};

	this.createRequestCallback = function(data, textStatus, scope, option) {
		if(!data) {
			return;
		}
		if(data.msg && data.msg == 208) {
			//todo 没有记录
			//scope.load(option.startIndex, option.buffer);
			alert(data.errmsg);
			return;
		} else if(data.msg && data.msg != 200) {
			alert(data.errmsg);
		}
		if(option.init){
			scope.tfeetCacheList.length=0;
		}
		for(var i = 0; i < data.tfeets.length; i++) {
			var thumbImg = preLoadImg(data.tfeets[i].tfeet.pic_small);
			jQuery(thumbImg).css({
				width : '100%',
				height : '100%'
			});
			var orgImg = preLoadImg(data.tfeets[i].tfeet.pic_original);
			var tfObj = new Tfeet.Tfobj({
				globeIndex : scope.tfeetCacheList.length,
				tfid : data.tfeets[i].tfeet.tfid,
				ds : data.tfeets[i],
				lng : data.tfeets[i].tfeet.long,
				lat : data.tfeets[i].tfeet.lat,
				location : data.tfeets[i].tfeet.location,
				description : data.tfeets[i].tfeet.text,
				orgImg : orgImg,
				thumbImg : thumbImg
			});
			scope.tfeetCacheList.push(tfObj);
		}
		scope.load(option.startIndex, option.buffer);

	}.createDelegate(this);
	this.setSelectedIndex = function(changeIndex) {
		changeIndex = Math.min(changeIndex, this.tfeetCacheList.length - 1);
		changeIndex = Math.max(changeIndex, 0);
		this.selectedIndex = changeIndex;
		this.trigger("SelectedChange", [this.selectedIndex]);
	};
	this.getSelectedIndex = function(offset) {
		if(!offset) {
			offset = 0;
		}
		return this.selectedIndex + offset;
	};

	this.createRequestErrorCallback = function(XMLHttpRequest, textStatus, errorThrown) {

		return function(options, success, response) {

		};
	}.createDelegate(this);

	this.initComponent(config);
};
Tfeet.Store.Extends(Tfeet.Base);

Tfeet.widgets.addTfeetWidget = function(config) {
	this.url = "/i/updatetfeet";
	this.el = jQuery('body');
	this.body = jQuery('<div class="frame"></div>');
	this.imgContainer = jQuery('<article class="infoImgContainer">拖个图片进来试试</article>');
	this.locationContainer = jQuery('<article class="infoLocContainer"><img src="../static/images/infobox/foot.png"/><input type="text" class="infoLocInput" x-webkit-speech x-webkit-grammar="bUIltin:search"/></article>');
	this.dateInput = jQuery('<input type="text" class="infoDateInput"/>');
	this.descriptContainer = jQuery('<textarea rows="3" cols="27" class="infoRemarkArea"></textarea>');
	this.commitBtn = jQuery('<div class="infoConfirmBtn"></div>');
	this.marker = null;
	this.infoBox = null;
	this.bo = null;
	this.geocoder = null;
	this.initComponent = function(config) {
		this.geocoder = new google.maps.Geocoder();
		Tfeet.apply(this, config);
		this.bo = new Tfeet.Tfobj();
		this.initEvent();
		//this.store.owner = this;
	};

	this.initEvent = function() {
		this.imgContainer.on({
			dragleave : function(e) {
				e.preventDefault();

			}.createDelegate(this),
			drop : function(e) {
				e.preventDefault();
				var orgEvent = e.originalEvent;
				//获取文件列表
				var fileList = orgEvent.dataTransfer.files;
				if(fileList.length > 1) {
					return false;
				}
				var img = new Image();

				//实例化file reader对象
				var reader = new FileReader();
				reader.onload = function(e) {
					img.src = this.result;
				}
				reader.readAsDataURL(fileList[0]);
				this.file = fileList[0];
				//reader.readAsBinaryString(fileList[0])
				jQuery(img).css({
					width : '100%',
					height : '100%'
				});
				this.imgContainer.html('');
				this.imgContainer.append(img);

			}.createDelegate(this),
			dragenter : function(e) {
				e.preventDefault();

			}.createDelegate(this),
			dragover : function(e) {
				e.preventDefault();
				this.addClass('infoImgContainer_ImgOver');
			}.createDelegate(this.imgContainer)
		});
		google.maps.event.addListener(map,'click',function(event){
			this.addTfeetMarker(event.latLng);
		}.createDelegate(this));
		this.commitBtn.click(this.commit);
	};
	/**
	 * 根据经纬度查询地址
	 */
	this.queryAddressFromLatLng = function(latLng){
		this.geocoder.geocode({'latLng': latLng}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				/*
				 * result 地址序列
				 * 0 最详细
				 * 1 区
				 * 2 城市
				 */
		        if (results[1]) {
					this.bo.location=results[1].formatted_address;
					this.locationContainer.find('.infoLocInput').val(this.bo.location);
			    }
			}
		}.createDelegate(this));
	}
	
	this.commit = function() {
		//window.URL.revokeObjectURL(file);
		var data = new FormData();
		data.append('myfile', this.file);
　		data.append('uid', this.uid);
　		data.append('text', this.descriptContainer.val());
		data.append('tfid','null');
		data.append('long',this.bo.lon);
		data.append('lat',this.bo.lat);
		data.append('location',this.bo.location);
		data.append('date',this.bo.dates);
		jQuery.ajax({
			url : this.url,
			contentType: 'multipart/form-data;boundary=--------AaB03x',
			type : 'POST',
			data: data,
			processData : false,
			beforeSend : function(event) {
				event.setRequestHeader("XSRCKEY", this.key);
			}.createDelegate(this),
			success : function(data) {
				alert(data);
			}
		})
	}.createDelegate(this);
	this.addTfeetMarker=function(location){
		this.bo.lon = location.lng();
		this.bo.lat = location.lat();
		if(this.marker==null){
			this.marker = new google.maps.Marker({
				position:location,
				map:map,
				draggable:true
			});
			if(this.infoBox==null){
				this.render();
				var myOptions = {
					content : this.body[0],
					disableAutoPan : false,
					maxWidth : 0,
					pixelOffset : new google.maps.Size(-152, -80),
					zIndex : null,
					boxClass : "frame",
					alignBottom : true,
					closeBoxMargin : "11px 10px 0px 0px",
					closeBoxURL : "../static/images/infobox/close.png",
					infoBoxClearance : new google.maps.Size(1, 1),
					isHidden : false,
					pane : "floatPane",
					enableEventPropagation : false
				};
				this.infoBox = new InfoBox(myOptions);
				google.maps.event.addListener(this.infoBox, 'closeclick', function(event) {
					this.marker.setMap(null);
					thumbList.showMarker();
					thumbList.el.slideToggle();
				}.createDelegate(this));
			}
			this.infoBox.open(map, this.marker);
			this.queryAddressFromLatLng(location);
			google.maps.event.addListener(this.marker,'dragstart',function(event){
				var newLocation = event.latLng;
				if(this.infoBox!=null){
					this.infoBox.hide();
				}
			}.createDelegate(this));
			google.maps.event.addListener(this.marker,'dragend',function(event){
				var newLocation = event.latLng;
				this.queryAddressFromLatLng(newLocation);
				this.bo.lon = event.latLng.lng();
				this.bo.lat = event.latLng.lat();
				if(this.infoBox!=null){
					this.infoBox.show();
				}
			}.createDelegate(this));
			google.maps.event.addListener(this.marker, 'click', function(event) {
				this.infoBox.open(map, this.marker);
			}.createDelegate(this));

		}
	};
	this.render = function() {
		this.body.html('');
		var bg = jQuery('<div class="infoBg"></div>');
		var shadow = jQuery('<div class="infoShadow"></div>');
		var footer = jQuery('<div class="infofooter"></div>');
		this.body.append(bg).append(shadow).append(this.imgContainer).append(this.locationContainer).append(this.dateInput).append(this.descriptContainer).append(this.commitBtn).append(footer);
		this.dateInput.wrap('<article class="infoDateContainer"></article>');
		var now = new Date();
		this.dateInput.val(now.format('yyyy年M月d日'));
		this.dateInput.DatePicker({
			format:'Y年m月d日',
			date: this.dateInput.val(),
			current: this.dateInput.val(),
			starts: 1,
			position: 'r',
			onBeforeShow: function(){
				this.bo.dates = this.dateInput.val();
				//this.dateInput.DatePickerSetDate(this.dateInput.val(), true);
			}.createDelegate(this),
			onChange: function(formated, dates){
				this.bo.dates = dates.format('yyyyMd');
				this.dateInput.val(formated);
				this.dateInput.DatePickerHide();
			}.createDelegate(this)
		});
	};
	this.initComponent(config);
};
Tfeet.widgets.addTfeetWidget.Extends(Tfeet.Base);
/**
 * 缩略图
 *
 * @param config
 * @returns {Tfeet.widgets.tfeetThumbList}
 */
Tfeet.widgets.tfeetThumbWidget = function(config) {
	this.el = jQuery('#thumb_container');
	this.maskBody = jQuery('<div id="thumbListMask"></div>');
	this.prevBtn = jQuery("<div id='thumb_prevbtn' class='thumb_btn'></div>");
	this.nextBtn = jQuery("<div id='thumb_nextbtn' class='thumb_btn'></div>");
	this.addBtn = jQuery("<div id='addBtn'></div>");
	this.body = jQuery('<div id="thumb_List"></div>');
	this.thumbDetailTpl = "<figcaption class='thumb_detail'>" + "<article>" + "<header>${uname}@${tfeet.location}</header>" + "<section>${tfeet.text}</section>" + "</article>" + "</figcaption>";
	this.markerList = new Array();
	this.store = null;
	this.mapBounds = null;
	this.currentIndex = 0;
	this.size = 10;
	this.initComponent = function(config) {
		Tfeet.apply(this, config);
		this.initEvent();
		this.store.owner = this;
	};

	this.initEvent = function() {
		this.store.bind('Load', this.processResponse);
		this.prevBtn.click(this.prev);
		this.nextBtn.click(this.next);
		this.addBtn.click(this.add);

	};
	this.add = function() {
		this.el.slideToggle();
		this.hideMarker();
		var addWidget = new Tfeet.widgets.addTfeetWidget({});
	}.createDelegate(this);
	/**
	 * 获取之前的tfeet
	 */
	this.prev = function() {
		this.currentIndex += this.size;
		this.store.load(this.currentIndex, this.size);

	}.createDelegate(this);
	/**
	 * 获取最新的tfeet
	 */
	this.next = function() {
		this.currentIndex -= this.size;
		this.store.load(this.currentIndex, this.size);
	}.createDelegate(this);

	this.setCurrent = function(currentIndex){
		this.currentIndex = currentIndex;
		this.store.load(this.currentIndex, this.size);
	}.createDelegate(this);
	

	this.processResponse = function(event, data) {
		//this.currentIndex = data;
		this.render();
	}.createDelegate(this);

	this.assembleThumb = function(columns){
		var thumbList = jQuery('.thumb_figure');
		var thumbHeight = thumbList.height()+10;
		var thumbWidth = thumbList.width()+10;
		var i=0;
		for(var row=0;row<2;row++){
			var offsetTop = this.el.height()/2-(thumbHeight+10);
			for(var col=0;col<columns;col++){
				var offsetLeft = (this.body.width()-5*(thumbWidth))/2;
				jQuery(thumbList[i]).css({"top":row*thumbHeight+offsetTop,"left":col*thumbWidth+offsetLeft}); 
				i++;
			}
		}
		
	}
	
	this.extendMapBounds = function(lat,lng){
		if(!this.mapBounds){
			var swLatLng = new google.maps.LatLng(lat,lng);
			var neLatLng = new google.maps.LatLng(lat,lng);
			this.mapBounds = new google.maps.LatLngBounds(swLatLng,neLatLng);
		}else{
			var latLng = new google.maps.LatLng(lat,lng);
			this.mapBounds.extend(latLng);
		}
	}
	
	this.hideMarker = function(){
		if(this.markerList){
			for(var i=0;i<this.markerList.length;i++){
				this.markerList[i].setMap(null);
			}
		}
	}
	
	this.showMarker = function(){
		if(this.markerList){
			for(var i=0;i<this.markerList.length;i++){
				this.markerList[i].setMap(map);
			}
		}
	}
	
	this.fitMap = function(){
		map.fitBounds(this.mapBounds);
	}
	
	this.markOnMap = function(data){
		var latLng = new google.maps.LatLng(data.lat,data.lng);
		var marker = new google.maps.Marker({
			position:latLng,
			title:data.ds.uname+"@"+data.ds.tfeet.location
		})
		marker.setMap(map);
		return marker;
	};
	this.flip = function(){
		jQuery('#location_side').removeClass("side_show");
		jQuery('#location_side').addClass("side_hide");
		jQuery('#gallery_side').removeClass("side_hide");
		jQuery('#gallery_side').addClass("side_show");
	};
	this.render = function() {
		this.el.empty();
		this.body.empty();
		var dataList = this.store.tfeetCacheList;
		this.hideMarker();
		this.mapBounds = null;
		this.markerList.length=0;
		for(var i = this.currentIndex; i < Math.min((this.currentIndex + this.size), dataList.length); i++) {
			var thumbTfContainer = jQuery("<figure class='thumb_figure'></figure>");
			var thumbImg = dataList[i].thumbImg;
			var $thumbDetail = jQuery.tmpl(this.thumbDetailTpl, dataList[i].ds);
			$thumbDetail.bind("click", {
				"globeIndex" : dataList[i].globeIndex
			}, function(event) {
				this.flip();
				gallery.setCurrent(event.data.globeIndex);
			}.createDelegate(this));
			thumbTfContainer.append(thumbImg).append($thumbDetail);
			thumbTfContainer.appendTo(this.body);
			this.extendMapBounds();
			this.markerList.push(this.markOnMap(dataList[i]));
		}
		this.body.append(this.prevBtn).append(this.nextBtn);
		this.el.append(this.maskBody).append(this.body);
		this.el.append(this.addBtn);
		this.assembleThumb(5);
		
	};

	this.initComponent(config);
};
Tfeet.widgets.tfeetThumbWidget.Extends(Tfeet.Base);

/**
 * 缩略图工具栏
 *
 * @param config
 * @returns {Tfeet.widgets.tfeetCommentWidget}
 */
Tfeet.widgets.tfeetGalleryToolbarWidget = function(config){
	this.gallery = null;
	this.el = jQuery("#gallery_toolbar_container");
	this.toolbarBody = jQuery("<div class='galleryToolbar galleryToolbar-transition'></div>");
	this.body = jQuery("<div class='galleryToolbarBody galleryToolbar-transition'></div>");
	this.favBtn = jQuery("<div class='galleryToolbar-btn galleryToolbar-fav-btn'></div>");
	this.returnBtn =  jQuery("<div class='galleryToolbar-btn galleryToolbar-return-btn'></div>");
	this.commentBtn = jQuery("<div class='galleryToolbar-btn galleryToolbar-comment-btn'></div>");
	this.infoBtn = jQuery("<div class='galleryToolbar-btn galleryToolbar-info-btn'></div>");
	this.prevBtn = jQuery("<div class='gallery_btn gallery_prev_btn galleryToolbar-transition'></div>");
	this.nextBtn = jQuery("<div class='gallery_btn gallery_next_btn galleryToolbar-transition'></div>");
	this.label = jQuery('<article class="gallery_label"></article>');
	this.mapPosition = jQuery("<div class='gallery_map'></div>");
	this.currentPageComentId = 0;
	this.commentListBody = jQuery("<div class='comment'><textarea rows='3' /><ul class='commentUl'></ul></div>");
	this.commentTpl = '<li><dl><dt><a class="comment-uname">${uname}</a>:</dt><dd>${comment}<span class="commentDate">(${DateFormat(datetime)})</span></dd>{{if uid=='+this.uid+'}}<span class="commentBtn" commentDelBtn>删除</span>{{/if}}</dl></li>'
	this.initComponent = function(config) {
		Tfeet.apply(this, config);
		this.initEvent();
	};
	this.initEvent = function(){
		this.commentListBody.find('textarea').on('keydown',function(event){
			if(event.keyCode==13){
				var target = event.currentTarget;
				this.submitComment(jQuery(target).val());
			}
		}.createDelegate(this));
		this.commentBtn.on('click',function(){
			this.commentListBody.toggleClass('comment-show');
			this.commentBtn.toggleClass('galleryToolbar-comment-btn');
			this.commentBtn.toggleClass('galleryToolbar-comment-btn-selected');
			if(this.commentListBody.hasClass('comment-show')){
				this.body.css('right',this.commentListBody.width()+'px');
			}else{
				this.body.css('right','0px');
			}
		}.createDelegate(this));
		this.prevBtn.on('click',this.gallery.prev);
		this.nextBtn.on('click',this.gallery.next);
		this.mapPosition.on('click',this.flip);
		this.favBtn.on('click',this.fav);
		this.returnBtn.on('click',this.flip);
		this.infoBtn.on('click',this.hide);
	};
	this.show = function(){
		this.el.show();
	};
	this.hide = function(){
		this.el.hide();
	};
	this.flip = function(){
		this.el.hide();
		jQuery('#gallery_side').addClass("side_hide");
		jQuery('#location_side').addClass("side_show");
		jQuery('#gallery_side').removeClass("side_show");
		jQuery('#location_side').removeClass("side_hide");
		
	}.createDelegate(this);
	this.initGalleryInfo = function(data){
		this.label.html('');
		this.label.append(jQuery("<p class='gallery_label_title'></p>").html(data.uname+'@'+data.location));
		this.label.append(jQuery("<p class='gallery_label_description'></p>").html(data.description));
	}.createDelegate(this);
	
	this.requestStaticMap = function(data){
		var googleUrl = "https://maps.googleapis.com/maps/api/staticmap?";
		googleUrl+="center="+data.lat+","+data.lng
		googleUrl+="&zoom="+8;
		googleUrl+="&size=200x200";
		googleUrl+="&markers=size:small%7Ccolor:blue%7Clabel:T%7C"+data.lat+","+data.lng
		googleUrl+="&sensor=true";
		this.mapPosition.html('');
		this.mapPosition.css({
			background:"url("+googleUrl+") no-repeat center center"
		});
		//this.mapPosition.wrap("<div class='gallery_map_container'></div>");
	}.createDelegate(this);
	this.fav = function(e,s,f){
		var target = jQuery(e.target);
		if(target.hasClass('galleryToolbar-fav-btn')){
			jQuery.ajax({
				url : "./i/addFav",
				type : "post",
				dataType : "json",
				data : {
					uid : this.uid,
					tfid : this.tfid
				},
				beforeSend : function(event) {
					event.setRequestHeader("XSRCKEY", this.key);
				}.createDelegate(this),
				success : function(data, textStatus) {
					debugger;
				}.createDelegate()
			});
		}else{
			jQuery.ajax({
				url : "./i/delFav",
				type : "post",
				dataType : "json",
				data : {
					uid : this.uid,
					tfid : this.tfid
				},
				beforeSend : function(event) {
					event.setRequestHeader("XSRCKEY", this.key);
				}.createDelegate(this),
				success : function(data, textStatus) {
					
				}.createDelegate()
			});
		}
		target.toggleClass('galleryToolbar-fav-btn').toggleClass('galleryToolbar-fav-btn-selected');
	}.createDelegate(this);
	this.submitComment = function(comment){
		jQuery.ajax({
			url : "./i/addComment",
			type : 'post',
			dataType : "json",
			data : {
				uid : this.uid,
				tfid:this.tfid,
				comment:comment
			},beforeSend : function(event) {
				event.setRequestHeader("XSRCKEY", this.key);
			}.createDelegate(this),
			success : function(data, textStatus) {
				if(data&&data.msg==200){
					var commentData = {
						uname:this.uname,
						cid:data.cid,
						uid:this.uid,
						comment:this.commentListBody.find('textarea').val(),
						datetime:data.date
					};
					var comment = jQuery.tmpl(this.commentTpl, commentData);
					this.commentListBody.find('ul').prepend(comment);
				}
			}.createDelegate(this)
		});
	};
	
	this.getComments = function(){
		jQuery.ajax({
			url : "./i/getComments/"+this.tfid,
			type : 'get',
			dataType : "json",
			data : {
				cid : this.currentPageComentId
			},
			beforeSend : function(event) {
				event.setRequestHeader("XSRCKEY", this.key);
			}.createDelegate(this),
			success:function(data){
				//this.nodeList = new Array();
				this.list = new Array();
				this.data = data;
				this.commentListBody.find('ul').html('');
				if (this.data["comments"] != null) {
					for ( var i = 0; i < this.data["comments"].length; i++) {
						var commentData = this.data["comments"][i];
						var comment = jQuery.tmpl(this.commentTpl, commentData);
						this.commentListBody.find('ul').append(comment);
					}
				}
			}.createDelegate(this)
		});
	}.createDelegate(this);
	
	this.render = function(){
		this.body.append(this.mapPosition).append(this.toolbarBody);
		this.toolbarBody.append(this.infoBtn).append(this.returnBtn).append(this.favBtn).append(this.commentBtn);
		this.el.append(this.label).append(this.prevBtn).append(this.nextBtn).append(this.commentListBody).append(this.body);
		this.el.show(500);
		this.getComments();
	};
	
	this.initComponent(config);
}
Tfeet.widgets.tfeetGalleryToolbarWidget.Extends(Tfeet.Base);

/**
 * 缩略图
 *
 * @param config
 * @returns {Tfeet.widgets.tfeetGallery}
 */
Tfeet.widgets.tfeetGalleryWidget = function(config) {
	this.current = 2;
	this.size = 5;
	this.galleryList = new Array();
	this.el = jQuery('#gallery_side');
	//this.prevBtn = jQuery("<div id='gallery_prevbtn' class='gallery_btn'></div>");
	//this.nextBtn = jQuery("<div id='gallery_nextbtn' class='gallery_btn'></div>");
	this.store = null;
	this.initComponent = function(config) {
		Tfeet.apply(this, config);
		
		this.initEvent();
		this.store.owner = this;
		this.toolbar = new Tfeet.widgets.tfeetGalleryToolbarWidget({gallery:this});
	};

	this.initEvent = function() {
		this.store.bind('Load', this.processResponse);
		this.store.bind('SelectedChange', this.processResponse);
		//注册键盘事件
		jQuery(document).keydown( function(event) {
			if(event.keyIdentifier == "Left") {
				this.prev();
			} else if(event.keyIdentifier == "Right") {
				this.next();
			}
		}.createDelegate(this));
		jQuery('body').on('hover',this.requestStaticMap);
		jQuery('figure[class*="gallery_center_"]').on('hover',this.showToolbar);
		jQuery('figure[class*="gallery_center_"]').on('mouseout',this.hideToolbar);
	};

	/* 显示工具与地图缩掠图 */
	this.showToolbar = function(event){
		var $target = jQuery(event.currentTarget);
		$target.find('.galleryToolbar').addClass('galleryToolbar-slide');
	}.createDelegate(this);
	/* 隐藏工具与地图缩掠图 */
	this.hideToolbar = function(event){
		var $target = jQuery(event.currentTarget);
		$target.find('.galleryToolbar').removeClass('galleryToolbar-slide');
	}.createDelegate(this);

	this.prev = function() {
		this.current++;
		this.setCurrent();
	}.createDelegate(this);

	this.next = function() {
		this.current--;
		this.setCurrent();
	}.createDelegate(this);

	this.setCurrent = function(selectedIndex) {
		if(selectedIndex) {
			this.current = selectedIndex;
		}
		//每当大图翻页判断是否需要同步缩略图模式
		if(this.current%thumbList.size==0){
			thumbList.setCurrent(this.current);
		}
		this.store.load(this.current, this.size);
		this.toolbar.render();
	};
	this.processResponse = function(event, data) {
		//this.dataList = data;
		this.render();
	}.createDelegate(this);

	this.render = function() {
		//this.el.empty();
		//this.body.empty();
		
		var dataList = this.store.tfeetCacheList;
		var startIndex = this.current - 2;
		var size = this.size + startIndex;
		var data = dataList[this.current];
		//for(var i = startIndex; i < Math.min(size, dataList.length); i++) {
		//var galleryList = this.bodywrap.children("figure");
		//for(var i=0;i<dataList.length;i++){
			if(data) {
				this.toolbar.requestStaticMap(data);
				this.toolbar.initGalleryInfo({
					uname:this.uname,
					location:data.location,
					description:data.description
				});
				var tfeetContainer = jQuery("<figure class='gallery_content'></figure>");
				var orgImg = data.orgImg;
				var clientHeight = document.documentElement.clientHeight-40;
				var clientWidth = document.documentElement.clientWidth;
				var top = (clientHeight-orgImg.naturalHeight+40)/2;
				var left = (clientWidth-orgImg.naturalWidth)/2;
				jQuery(orgImg).css({
					width : orgImg.naturalWidth+"px",
					height : orgImg.naturalHeight+"px",
					"margin-left":left+"px",
					"margin-top":top+"px"
				});
				
				tfeetContainer.append(orgImg).appendTo(this.el);
				this.toolbar.tfid = data.tfid;
				//jQuery(galleryList[i]).html("").append(orgImg).append(abstract);
				//toolbar.render();
			}
		//}
		
	};

	this.initComponent(config);
};
Tfeet.widgets.tfeetGalleryWidget.Extends(Tfeet.Base);
